package org.bite.lesson07;

public class MyBlockingQueue {
    private Integer[] elementData;
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;

    public MyBlockingQueue(int capacity){
        if(capacity <= 0){
            throw new RuntimeException("元素个数不能小于等于0");
        }
        elementData = new Integer[capacity];
    }

    /**
     * put方法
     */
    public void put(Integer value) throws InterruptedException{
        synchronized(this){
            while(size >= elementData.length){
                this.wait();
            }
            elementData[tail] = value;
            tail++;
            if(tail >= elementData.length){
                tail = 0;
            }
            size++;
            this.notifyAll();
        }
    }
    /**
     * take方法
     */
    public synchronized Integer take() throws InterruptedException{
        while(size == 0){
            this.wait();
        }
        Integer value = elementData[head];
        head++;
        if(head >= elementData.length){
            head = 0;
        }
        size--;
        this.notifyAll();
        return value;
    }
}
